<template>
  <div class="common-box AbnormalScan">
    <v-header :headerName="headerName" :orderList="orderList"></v-header>
    <div class="content-box">
      <v-scan @scanData="scanData" :switchScan="switchScan" :loadingData="loadingData"></v-scan>
    </div>
    <div class="order-level level2">
      <el-tabs v-model="activeName" :stretch="true" v-loading="loadingData">
        <el-tab-pane :label="'扫描子单(' + orderList.length + ')'" name="first">
          <div class="order-header">
            运单号({{ orderList.length }})
          </div>
          <div class="order-list">
            <div class="list-item" v-for="(item, idx) in orderList" :key='idx + "i"'>
              {{item.order}}
            </div>
          </div>
          <div class="no-data" v-show="orderList.length == 0">
            <div class="right-bg"></div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="'历史子单('+ historyLabelNo.length + ')'" name="second">
          <div class="order-list">
            <div class="list-item" v-for="(item, hidx) in historyLabelNo" :key='hidx + "k"'>
              {{ item }}
            </div>
          </div>
          <div class="no-data no-data2" v-show="historyLabelNo.length == 0">
            <div class="right-bg"></div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="'未扫描子单(' + notScanLabelNo.length + ')'" name="third">
          <div class="order-list">
            <div class="list-item" v-for="(item, nidx) in notScanLabelNo" :key='nidx + "w"'>
              {{ item }}
            </div>
          </div>
          <div class="no-data no-data2" v-show="notScanLabelNo.length == 0">
            <div class="right-bg"></div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div class="Upload">
        <div class="uploadImg">
          <v-uploader title="拍照上传(限4张)" :url="abnormalUploadImage" :limit="4" ref="upload_refAbScan" name="file"
            :isNotice="false" :params="uploadParams" />
        </div>
      </div>
    </div>
    <v-footer :count="orderList" :orderCount="orderCodeList.filter(item => {return item !== ''}).length"
      :countData="countData" @reflash="reflashData" @scanFun="switchScanFun" :orderList="cleanOrderList"
      :deliveryId='deliveryId' :transportLinks='transportLinks' :actualQty="actualQty" :abnormalscan='abnormalscan'
      :omsNo="omsNo" :orderId="orderId" :AbHasScanNum="AbHasScanNum" :chargeTypes="chargeTypes" :destType="destType" @isLoading_="fullscreenLoading">
    </v-footer>
    <v-confirm ref="message"></v-confirm>
  </div>
</template>
<script>
import Header from '@/components/header'
import Scan from '@/components/Scan'
import AbnormalFooter from '@/components/abnormalFooter'
import Confirm from '@/components/confirm'
import Uploader from '@/components/uploader'
import { getTheOrderNumber1, abnormalUploadImage } from "../../../api/api";
import $ from "jquery"
export default {
  name: "AbnormalScan",
  components: {
    'v-header': Header, // 头部组件
    'v-scan': Scan,  // 扫描组件
    'v-footer': AbnormalFooter,  // 提交组件
    'v-confirm': Confirm,
    'v-uploader': Uploader // 上传组件
  },
  data() {
    return {
      abnormalUploadImage,
      activeName: 'first',
      headerName: '异常单签收',
      orderCount: 0, // 订单号数量统计
      countData: [], // 需要提交给后台的对象数组
      orderList: [], // 运单号列表
      orderCodeList: [], // 订单号列表
      cleanOrderList: [], // 只有运单号的数组
      scanLabelNo: [], // 本次扫描的标签好列表
      historyLabelNo: [], // 历史标签号数据数组
      notScanLabelNo: [], // 未扫描标签号数据
      uploadParams: {},//上传图片时 额外的参数
      loadingData: false,
      linkNode: '',
      switchScan: true,
      shipmentCode: '',//配载单号
      deliveryId: '',//运单id
      omsNo: '',//订单号
      orderId: '',//订单id
      LocateAbnormalScanLabel: '',//定位异常单页面传来的标签号
      transportLinks: '',//扫描环节
      actualQty: 0,//订单总件数
      abnormalscan: true,//异常签收
      AbHasScanNum: 0,//异常已签收数量
      destType: '', // 是否强制转寄（网点）
      chargeTypes: '' // 付款方式
    }
  },
  mounted() {
    switch (this.$route.path) {
      case '/AbnormalScan':
        this.linkNode = '40'
        break
      default:
        this.linkNode = '10'
        break
    }
    let that = this;
    $('.LoadImg_conentul ul.el-upload-list+div').click(function (e) {
      event.stopPropagation();
      that.switchScanFun(false); // 关闭摄像头
    })
  },
  created() {
    if (this.$route.query.shipmentCode) {
      this.shipmentCode = this.$route.query.shipmentCode;
    }
    if (this.$route.query.deliveryId) {
      this.deliveryId = this.$route.query.deliveryId;
    }
    if (this.$route.query.omsNo) {
      this.omsNo = this.$route.query.omsNo;
    }
    this.uploadParams.omsNo = this.omsNo;//订单号
    this.uploadParams.fileType = 'wxReceipt';//上传的类型 异常上传
    if (this.$route.query.orderId) {
      this.orderId = this.$route.query.orderId;
    }
    if (this.$route.query.transportLinks) {
      this.transportLinks = this.$route.query.transportLinks;
    }
    if (this.$route.query.actualQty) {
      this.actualQty = this.$route.query.actualQty;
    }
    if (this.$route.query.AbHasScanNum) {
      this.AbHasScanNum = this.$route.query.AbHasScanNum;
    }
    if (this.$route.query.LocateAbnormalScanLabel) {
      this.LocateAbnormalScanLabel = this.$route.query.LocateAbnormalScanLabel;
    }
    if (this.$route.query.destType) {
      this.destType = this.$route.query.destType;
    }
    if (this.$route.query.chargeTypes) {
      this.chargeTypes = this.$route.query.chargeTypes;
    }
  },
  methods: {
    // 上传图片
    updateimg() {
      this.uploadParams.omsNo = this.omsNo;
      this.uploadParams.fileType = '签收';
      this.uploadParams.labelNo = '40'; // 扫描环节
      let refAbScanAsync = this.$refs.upload_refAbScan.submit(this);
      refAbScanAsync.then((res) => {
        this.finishUpload('图片上传成功')
      }).catch(() => {
        this.finishUpload('图片上传失败')
      })
    },
    // 加载特效出现  子传父事件
    "fullscreenLoading"(isLoad, loadingText) {
      this.$emit('isLoading', isLoad, loadingText);
    },
    goprev() {
      let that = this;
      if (this.LocateAbnormalScanLabel) {
        this.$router.push({
          name: "ScanQueryOrderInfo",
          query: {
            LocateAbnormalScanLabel: that.LocateAbnormalScanLabel
          }
        })
      } else {
        this.$router.back(-1);
      }
    },
    switchScanFun(data) {
      if (data) {
        this.switchScan = true // 打开摄像头
      } else {
        this.switchScan = false // 关闭摄像头
      }
    },
    // 提示框
    userBehaviorFun() {},
    /**
     * 删除单条不要的数据
     **/
    deleteItem(key) {
      this.orderList = this.orderList.filter(item => {
        return item.order !== key
      })
      let arr = []
      for (let i in this.orderList) {
        arr.push(this.orderList[i]['orderBooting'])
      }
      // 去重
      function unique(list) {
        return Array.from(new Set(list))
      }
      this.orderCodeList = unique(arr)
      this.cleanOrderList = []
      for (let item in this.orderList) {
        this.cleanOrderList.push(this.orderList[item].order)
      }
    },
    /**
     * 提交成功清空数据
     **/
    reflashData() {
      this.countData = []
      this.orderList = []
      this.orderCodeList = []
      this.cleanOrderList = []
      this.scanLabelNo = [] // 本次扫描的标签好列表
      this.historyLabelNo = [] // 历史标签号数据数组
      this.notScanLabelNo = []// 未扫描标签号数据
    },
    /**
     * 从子组件{scan.vue}获取传过来的数据
     * @param data 标签号
     */
    scanData(data) {
      let _this = this;
      // 如果默认的历史标签数据与未扫描数据数组为空，说明这是新开的界面，需要请求比对数据
      if (this.historyLabelNo.length === 0 && this.notScanLabelNo.length === 0 && this.orderList.length === 0) {
        let params = {
          scanLabel: data,
          linkNode: this.linkNode,
          omsNo: _this.omsNo
        }
        this.getTheOrderNum(params, data)
      } else { // 历史数据与未扫描数据数组不为空，有比对数据，先进行数据对比
        _this.step0(data).then(data0 => { // 当前扫描中的列表数据是否有相同数据
          if (data0.length !== 0) {
            _this.$refs.message.show('该标签号已扫描过!', {
              type: 'alert',
              confirmText: '确定',
              titleText: '请注意',
            })
          } else {
            _this.step1(data).then(data1 => {
              if (data1.length !== 0) { // 在旧历史数据中有关联的标签号，提示用户保存过该数据
                _this.$refs.message.show('该标签号已扫描保存过!', {
                  type: 'alert',
                  confirmText: '确定',
                  titleText: '请注意',
                })
              } else {
                _this.step2(data).then(data2 => {
                  if (data2.length !== 0) { // 在未保存数据中有相应的标签号，直接在标签号列表添加相应的标签号
                    this.orderList.push({
                      order: data,
                      orderBooting: '',
                      time: this.getTheTimeNow()
                    })
                    // 删除添加到扫描标签的未扫描标签
                    this.notScanLabelNo = this.notScanLabelNo.filter(item => {
                      return item !== data
                    })
                  } else {
                    let params = {
                      scanLabel: data,
                      linkNode: this.linkNode,
                      omsNo: _this.omsNo
                    }
                    this.getTheOrderNum(params, data)
                  }
                })
              }
            })
          }
        })
      }
    },
    /**
     * 获取当前扫描时候的数据时间
     **/
    getTheTimeNow() {
      const date = new Date()
      let year = date.getFullYear()
      let month = checkVal(date.getMonth() + 1)
      let day = checkVal(date.getDay())
      let hour = checkVal(date.getHours())
      let min = checkVal(date.getMinutes())
      let sec = checkVal(date.getSeconds())
      function checkVal(val) {
        if (val < 10) {
          return '0' + val
        } else {
          return val
        }
      }
      return `${year}-${month}-${day} ${hour}:${min}:${sec}`
    },
    /**
     * 数组去重方法
     **/
    distinct(a, b) {
      let arr = a.concat(b)
      let result = []
      let obj = {}
      for (let i of arr) {
        if (!obj[i]) {
          result.push(i)
          obj[i] = 1
        }
      }
      return result
    },
    // 0. 检测扫描标签中是否存在正在扫描的标签，有的话提示已扫描，否则进入下一步
    step0(val) {
      let _this = this
      return new Promise(resolve => {
        let arr = _this.orderList.filter(item => {
          return item.order == val
        })
        resolve(arr)
      })
    },
    // 1. 检测比对历史数据以及未扫描数据，排查是否存在该标签号
    step1(val) {
      let _this = this
      return new Promise((resolve, reject) => {
        let arr = _this.historyLabelNo.filter(item => {
          return item == val
        })
        resolve(arr)
      })
    },
    // 2. 当比对历史数据不存在扫描到的标签号的时候再查询未查询扫描信息的列表进行比对
    step2(val) {
      let _this = this
      return new Promise((resolve, reject) => {
        let arr = _this.notScanLabelNo.filter(item => {
          return item == val
        })
        resolve(arr)
      })
    },
    /**
     * 调用接口{ getTheOrderNumber }获取运单的订单号
     * @param params 请求的传参{ 扫描的标签号 }，data { 标签号 }
     */
    getTheOrderNum(params, data) {
      let _this = this
      this.loadingData = true
      this.propScanData = data
      this.httpRequest1('post', getTheOrderNumber1, params).then(res => {
        _this.loadingData = false;
        let obj = res.entity;
        function reSetData() {
          return new Promise(resolve => {
            // 首先整合请求到的数据列表
            _this.historyLabelNo = _this.historyLabelNo.concat(obj.historySubmitLabelNo)
            _this.notScanLabelNo = _this.notScanLabelNo.concat(obj.notScanLabelNo)
            // 数组去重
            function unique(list) {
              return Array.from(new Set(list))
            }
            _this.historyLabelNo = unique(_this.historyLabelNo)
            _this.notScanLabelNo = unique(_this.notScanLabelNo)
            resolve(true)
          })
        }
        reSetData().then(resolve => {
          if (resolve) {
            // 逻辑运行
            _this.step1(data).then(data1 => {
              if (data1.length !== 0) { // 1. 当匹配到的数据存在的时候，提示用户该标签号曾经扫描保存过
                _this.$refs.message.show('该标签号已扫描保存过!', {
                  type: 'alert',
                  confirmText: '确定',
                  titleText: '请注意',
                })
                this.orderCodeList = this.distinct(this.orderCodeList, obj.omsNo)
              } else {
                _this.step2(data).then(data2 => { // 2. 当历史保存数据中没搜索到相关记录，再查找未扫描的标签号是否存在这个正在扫描的标签号
                  if (data2.length !== 0) { // 在未扫描数据中匹配到该未扫描标签号，保存起来展示到列表中
                    this.orderList.push({
                      order: data,
                      orderBooting: obj.omsNo,
                      time: this.getTheTimeNow()
                    })
                    // 删除添加到扫描标签的未扫描标签
                    this.notScanLabelNo = this.notScanLabelNo.filter(item => {
                      return item !== data
                    })
                    this.orderCodeList = this.distinct(this.orderCodeList, obj.omsNo)
                  } else { // 保存的数据与未保存的历史数据都不存在该记录的话则是因为不存在该标签号，提示用户标签号错误
                    _this.$refs.message.show('标签号错误，请重新扫描!', {
                      type: 'alert',
                      confirmText: '确定',
                      titleText: '请注意',
                    })
                  }
                })
              }
            })
          }
        })
        this.cleanOrderList = []
        for (let item in this.orderList) {
          this.cleanOrderList.push(this.orderList[item].order)
        }
      }).catch(err => {
        _this.loadingData = false
      })
    },
    //上传完成后（包含部分上传失败）
    finishUpload(text) {
      let that = this;
      that.$emit('isLoading_', false);
      text = text ? "," + text : "";
      this.$alert("扫描保存成功" + text, '提示', {
        confirmButtonText: '确定',
        callback() {
          that.$router.back(-1);
        }
      })
    }
  }
}
</script>
<style scoped lang="less">
.common-box {
  height: 100%;
}
.Upload {
  font-size: 28/50rem;
  display: block;
  .uploadImg > div {
    float: static;
    margin-bottom: 10/50rem;
  }
}
</style>